# -*- coding: utf-8 -*-
import random
import MySQLdb


def insert_list(word_list, host, class_id, class_name, round_id, orders, random_need=True, word_count = 14, db_user="root",db_passwd="totoro", db_name="magic"):
    # round_id为当前最后一个round的id
    if random_need:
        random.shuffle(word_list)

    db= MySQLdb.connect(
            host = host,
            port = 3306,
            user=db_user,
            passwd=db_passwd,
            db =db_name,
            charset='utf8',
            )
    cursor = db.cursor()

    sql = '''INSERT INTO totoro_class(id, class_name, parent_id, is_leaf, word_count, class_type,orders)
                        VALUES ('%s', '%s', '%d', '%d', '%d', '%d', '%d')''' % (class_id, class_name, 53, 1, len(word_list), 1, orders)
    print sql
    cursor.execute(sql)
    db.commit()
    sql = '''INSERT INTO word_master_frequence(class_id, class_name, frequence)
                        VALUES ('%s', '%s', '%d')''' % (class_id, class_name, 5)
    print sql
    cursor.execute(sql)
    db.commit()

    orders = 1
    i = 1
    for w in word_list:
        if i == 1:
            round_name = "第"+str(orders)+"关"
            round_id +=1
            round_desc = class_name + round_name
            sql =  '''INSERT INTO totoro_round(id, round_name, round_desc, class_id, class_name, word_count,orders)
                        VALUES ('%s', '%s', '%s', '%d', '%s', '%d', '%d')''' % (round_id, round_name, round_desc, class_id, class_name, word_count,orders)
            print sql
            cursor.execute(sql)
            db.commit()


            orders+=1
        word = w[0]
        word_zh = w[1]
        voice = 'yd-'+word
        sql = '''INSERT INTO word(round_id, round_name, class_id, class_name, word, word_zh, voice)
                    VALUES('%d', '%s', '%d', '%s', "%s", "%s", "%s")''' % (round_id, round_name, class_id, class_name, word, word_zh, voice)
        cursor.execute(sql)
        db.commit()
        i +=1
        if i>14:
            i=1
    db.close()


def modify_word_voice(word, host, cite, db_user="root",db_passwd="totoro", db_name="magic"):
    db = MySQLdb.connect(
            host = host,
            port = 3306,
            user=db_user,
            passwd=db_passwd,
            db =db_name,
            charset='utf8',
            )
    cursor = db.cursor()
    sql = '''update word set voice = "%s" where word = "%s";''' % (cite+"-"+word, word)
    print sql
    cursor.execute(sql)
    db.commit()
